/*
 * To change this license header, choose License Headers in Project Properties.
 * To change this template file, choose Tools | Templates
 * and open the template in the editor.
 */
package com.chl.mq._06_properties;

import com.alibaba.fastjson.JSON;
import com.rabbitmq.client.Channel;
import com.rabbitmq.client.Connection;
import com.rabbitmq.client.ConnectionFactory;
import java.io.File;
import java.io.IOException;
import java.util.List;
import java.util.Map;
import org.apache.commons.io.FileUtils;

/**
 *
 * @author 陈宏亮
 */
public class PropertiesInit {
    public static void main(String[] args) throws Exception {
        ConnectionFactory factory = new ConnectionFactory();
//        factory.setHost("192.168.3.110");
//        factory.setUsername("waytogo");
//        factory.setPassword("123456");
//        factory.setHost("192.168.3.147");
//        factory.setUsername("guest");
//        factory.setPassword("guest");
        factory.setHost("192.168.0.221");
        factory.setUsername("guest");
        factory.setPassword("guest");
        factory.setVirtualHost("testc");
        try (Connection connection = factory.newConnection()) {
            Channel channel = connection.createChannel();
            init(channel, getConfig("target\\classes\\mail.config.json"));
            channel.close();
        }
    }
    
    public static void init(Channel channel, Map<String, Object> config) throws IOException {
        List<Map<String, Object>> exchanges = (List<Map<String, Object>>) config.get("exchanges");
        
        for (int i = 0; i < exchanges.size(); i++) {
            Map<String, Object> exchange = exchanges.get(i);
            String name = (String) exchange.get("name");
            String exType = (String) exchange.get("exType");
            Boolean durable = Boolean.TRUE.equals((Boolean) exchange.get("durable"));
            channel.exchangeDeclare(name, exType, durable);
        }
        
        List<Map<String, Object>> queues = (List<Map<String, Object>>) config.get("queues");
        for (int i = 0; i < queues.size(); i++) {
            Map<String, Object> queue = queues.get(i);
            String name = (String) queue.get("name");
            String exchange = (String) queue.get("exchange");
            String routeKeys = (String) queue.get("routeKeys");
            Boolean durable = Boolean.TRUE.equals((Boolean) queue.get("durable"));
            Map<String, Object> options = (Map<String, Object>) queue.get("options");
            channel.queueDeclare(name, durable, false, false, options);
            channel.queueBind(name, exchange, routeKeys);
        }
        
    }
    public static Map<String, Object> getConfig(String path) throws IOException {
        String str = FileUtils.readFileToString(new File(path), "utf8");
        Map<String, Object> config = JSON.parseObject(str, Map.class);
        System.out.println(config);
        return config;
    }
}
